package com.tuyrt.`as`.proj.main.route

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.alibaba.android.arouter.launcher.ARouter
import com.tuyrt.`as`.proj.main.biz.account.AccountManager
import com.tuyrt.hi.library.util.MainHandler

/**
 * author: Administrator on 2021/6/8.
 * desc:
 */
@Interceptor(name = "biz_interceptor", priority = 9)
open class BizInterceptor : IInterceptor {

    private var context: Context? = null

    override fun init(context: Context?) {
        this.context = context
    }

    /**
     *  note: 该方法运行在 ARouter的线程池中
     */
    override fun process(postcard: Postcard?, callback: InterceptorCallback?) {
        val flag = postcard!!.extra
        if ((flag and RouteFlag.FLAG_LOGIN) != 0) {
            // login
            callback!!.onInterrupt(RuntimeException("need login"))
           loginIfNecessary(postcard,callback)
        }
//        else if (flag and RouteFlag.FLAG_AUTHENTICATION != 0) {
//            callback!!.onInterrupt(RuntimeException("need authentication"))
//            showToast("请先实名认证")
//            // authentication
//        }else if (flag and RouteFlag.FLAG_VIP != 0) {
//            callback!!.onInterrupt(RuntimeException("need become vip"))
//            showToast("请先加入会员")
//        }
        else {
            callback!!.onContinue(postcard)
        }
    }

    private fun loginIfNecessary(postcard: Postcard?, callback: InterceptorCallback?) {
        MainHandler.post {
            if (AccountManager.isLogin()) {
                callback?.onContinue(postcard)
            } else {
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show()
                AccountManager.login(context) {
                    callback?.onContinue(postcard)
                }
            }
        }
    }


    private fun showToast(message: String) {
        Handler(Looper.getMainLooper()).post {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
        }
    }
}